<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Db;
use app\common\model\Gamearea;
use app\common\model\Gamelist;
use app\common\model\User;
use app\common\model\Gamesupply;
use app\common\model\GameOrderNotify;


/**
 * 游戏管理
 * Class AdminUser
 * @package app\admin\controller
 */
class Game extends AdminBase
{

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 用户管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index()
    {
        $map  = [];
        $data = input();
        $page = $data['page'] ?? 1;
        if (!empty($data['name'])) {
            $map[] = ['name','like', "%{$data['name']}%"];
        }else{
            $data['name']='';
        }
        if (!empty($data['status'])) {
            $map[] = ['gstatus','=', $data['status'] - 1];
        }else{
            $map[] = ['gstatus','>=', 0];
            $data['status']='0';
        }

        if (!empty($data['game'])) {
            $map[] = ['id','=', $data['game']];
        }

        if (!empty($data['gchannel'])) {
            $map[] = ['gchannel','like', "%{$data['gchannel']}%"];
        }
        $game_list = Gamelist::get_list($map, 'id DESC', $page, $data);
        $game_url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST']."/game/play";
        $this->assign('game_url',$game_url);
        return $this->fetch('index', ['game_list' => $game_list,'data' => $data]);
    }
	
    /**
     * 添加游戏
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }
	
    /**
     * 保存游戏
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'GameList');
			if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data['login_key']=md5(time().rand(100000, 999999));
                $data['pay_key']=md5(time().rand(100000, 999999));
                if (Gamelist::insert($data)) {
                    $this->success('保存成功','/admin/game');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }
	
    /**
     * 编辑游戏
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $game = Gamelist::find($id);
        return $this->fetch('edit', ['game' => $game]);
    }

    /**
     * 更新游戏
     * @param $id
     */
    public function update()
    {
        if ($this->request->isPost()) {
            
            $data            = $this->request->post();
		    $validate_result = $this->validate($data, 'GameList');
            $id = $data['id'];
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
			    if ($game=Gamelist::where('id',$id)->update($data)) {
                    $this->success('更新成功','/admin/game');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }
	
    /**
     * 游戏总状态更改,一旦关闭 登录接口关闭,支付接口关闭
     * @param $id
     */
    public function check()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $tp = $this->request->post('tp');
            $val = $this->request->post('val');
			    $game               = Gamelist::find($id);

                if($game['gfencheng'] <= 0){
                    $this->error('请设置CP分成');
                }
                $game->id           = $id;

                switch($tp)
                {
                    case "gstatus":
                    $game->gstatus       = $val;
                    break;
                    case "pstatus":
                    $game->pstatus       = $val;
                    break;
                    case "status":
                    $game->status       = $val;
                    break;
                }
                if($tp=='status' && $val==0)
                {
                $game->gstatus       = $val;
                $game->pstatus       = $val;
                }
                if ($game->save()) {
                    $this->success('更改成功');
                } else {
                    $this->error('更改失败');
                }
            }
    }
	
    /**
     * 删除游戏
     * @param $id
     */
    // public function delete($id)
    // {
        // if ($this->glist_model->destroy($id)) {
            // $this->success('删除成功');
        // } else {
            // $this->error('删除失败');
        // }
    // }
	
    /**
     * 补单记录
     * @return mixed
     */
    public  function supply()
    {
        $map  = [];
        $data = input();
        if(!empty($data['keyword'])){
            $map[]  = ['order_no','like', '%'.$data['keyword'].'%'];
        }
        if (!empty($data['starttime']) && !empty($data['endtime'])) {
            $map[]= ['notify_time','between time',[strtotime($data['starttime']),strtotime($data['endtime'])]];
        }elseif (!empty($data['starttime'])) {
            $map[] = ['notify_time','>=',strtotime($data['starttime'])];
        }elseif (!empty($data['endtime'])) {
            $map[] = ['notify_time','<=',strtotime($data['endtime'])];
        }
        if(!empty($data['game'])){
            $map[]   =['gid','=',(int)input('game')];
        }else{
            $data['game']   = null;
        }
        
        $game_list = GameOrderNotify::where($map)->order('id desc')->paginate(15);
        return $this->fetch('supply', ['game_list' => $game_list,'data'=>$data]);
    }
    
    /**
     * 补单
     */
    public function supply_oeder($id){
        if(!$id){
            return json(array('msg'=>"数据错误！"));exit;
        }
        $supply = DB::name('gamesupply')->where(array('id'=>$id))->find();
        if(empty($supply) && !isset($supply)){
            return json(array('msg'=>"订单错误！"));exit;
        }
        if($supply['pay_status'] == 1){
            return json(array('msg'=>"订单已补，请勿重复操作。。"));exit;
        }
        //写入游戏数据库
        $status = $this->send_supply($supply);
        if($status && DB::name('gamesupply')->where(array('id'=>$id))->update(['pay_status'=>1])){
            return json(array('msg'=>"补单成功！"));
        }else{
            return json(array('msg'=>"补单失败，请稍后再试。。。"));exit;
        }
    }

    /**
     * @return array
     * 游戏cp管理
     */
    public function cpgame()
    {
        $map  = [];
        $data = input();
        if(!empty($data['keyword'])){
            $map[]  = ['cp_name','like', '%'.$data['keyword'].'%'];
        }
        if (!empty($data['starttime']) && !empty($data['endtime'])) {
            $map[]= ['create_time','between time',[strtotime($data['starttime']),strtotime($data['endtime'])]];
        }elseif (!empty($data['starttime'])) {
            $map[] = ['create_time','>=',strtotime($data['starttime'])];
        }elseif (!empty($data['endtime'])) {
            $map[] = ['create_time','<=',strtotime($data['endtime'])];
        }
        if(!empty($data['game'])){
            $map[]   =['gid','=',(int)input('game')];
        }else{
            $data['game']   = null;
        }
        $game_list = GameCp::where($map)->order('id desc')->paginate(15);
        return $this->fetch('cpgame', ['game_list' => $game_list,'data'=>$data]);
    }
    
    /**
     * 游戏补单
     */
    protected function send_supply($data){
        //游戏数据
        $map = [];
        $map['gameapi_gamearea.gid'] = $data['gid'];
        $map['gameapi_gamearea.sid'] = $data['sid'];
        //获取游戏信息
        $game=Gamelist::getgamedata($get['gid']);
        //校验代理状态
        $user=User::get($get['agent']);
        if(empty($user)) return json(['code'=>'-1003','msg'=>'代理不存在']);
        if($user['status']!=1) return json(['code'=>'-1004','msg'=>'代理状态异常']);
        
        $cname=ucwords($game['gchannel']);
         $gameplogData['uid_md5']=$user['platform'].'_'.substr(md5($data['uid']),8,16);
         
         //判断区服状态
         $gamearea=Gamearea::getInfo($get['gid'],$get['sid']);
        $gameplogData['areainfo']=$gamearea;
        
        unset($data['id']);
        unset($data['pay_time']);
        unset($data['note']);
        $gameplogData = $data;
        $gameapi = \think\facade\App::controller("common/{$cname}", 'gameapi');
        $code=$gameapi->beginRecharge($gameplogData);
         return $code;   
        }
        
    }
